﻿function ShanbayAPI() {
    this.host = "http://www.shanbay.com";
    this.ADD_WORD_API = this.host + '/api/learning/add/{{word}}';
}

function isEnglish(s) {
    var pattern = /^[A-Za-z ]+$/;
    if (!pattern.exec(s)) {
        return false;
    } else {
        return true;
    }
}

ShanbayAPI.prototype.sendRequest = function (url, handler) {
    console.log("request url: " + url);
    var req = new XMLHttpRequest();
    req.onreadystatechange = function (data) {
        if (req.readyState != 4) {
            return;
        }
        if (req.status != 200) {
            handler(null);
            return;
        }
        var data = req.responseText;
        console.log("http response: " + data);
        var obj = null;
        try {
            obj = JSON.parse(data);
        } catch (e) {
            this.report("parse json failed!, ", e);
        }
        handler(obj);
    }
    req.open('GET', url, true);
    req.send(null);
}

ShanbayAPI.prototype.getAPIURL = function (api, args) {
    var i, result = api, lens = arguments.length;
    for (i = 1; i < lens; i++) {
        result = result.replace(/{{.+?}}/, arguments[i]);
    }
    return result;
}

ShanbayAPI.prototype.report = function (message, e) {
    console.log("[api==>]" + message + " Error: " + e);
}

ShanbayAPI.prototype.getLearnWordUrl = function (wordID) {
    return "http://www.shanbay.com/learning/" + wordID + "/";
}

ShanbayAPI.prototype.addWord = function (word, handler) {
    if (word == "") {
        handler(null);
        return;
    }

    if (!isEnglish(word)) {
        handler(null);
        return;
    }

    this.sendRequest(this.getAPIURL(this.ADD_WORD_API, word), handler);
}

ShanbayAPI.prototype.getUser = function(handler) {
    var details = new Object();
    // details.url = this.host;
    // details.name = "username";
    // chrome.cookies.get( // I don't know why this cannot work any more. :(
    chrome.cookies.getAll(
        details,
		function(cookies) {
		    for (var i = 0; i < cookies.length; ++i) {
		        console.log("cookie: " + cookies[i].name + " = " + cookies[i].value);
		        if (cookies[i].name == "username") {
		            handler(cookies[i].value);
		            return;
		        }
		    }
		    handler(null);
		}
	);
}

ShanbayAPI.prototype.getUserURL = function (user) {
    return this.host + '/user/list/' + user + '/';
}

ShanbayAPI.prototype.getLoginURL = function () {
    return this.host + '/accounts/login/';
}